package login.panel;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.*;

import chat.frame.ChatInterface;
import cn.hutool.core.util.StrUtil;
import login.frame.LoginFrame;

public class LoginPanel extends ParentPanel {

	private static final long serialVersionUID = 1L;

	// Material Design 3 配色方案
	private static final Color BACKGROUND_COLOR = new Color(252, 248, 253);
	private static final Color SURFACE_COLOR = new Color(255, 255, 255);
	private static final Color PRIMARY_COLOR = new Color(103, 80, 164);
	private static final Color ON_SURFACE_COLOR = new Color(28, 27, 31);
	private static final Color ON_SURFACE_VARIANT_COLOR = new Color(73, 69, 79);
	private static final Color OUTLINE_COLOR = new Color(201, 196, 206);
	private static final Color ERROR_COLOR = new Color(244, 67, 54);
	private static final Color SUCCESS_COLOR = new Color(76, 175, 80);
	
	// 现代化字体
	private static final Font TITLE_FONT = new Font("微软雅黑", Font.BOLD, 24);
	private static final Font BODY_FONT = new Font("微软雅黑", Font.PLAIN, 14);
	private static final Font INPUT_FONT = new Font("微软雅黑", Font.PLAIN, 16);
	
	// 间距常量
	private static final int SMALL_SPACING = 8;
	private static final int MEDIUM_SPACING = 16;
	private static final int LARGE_SPACING = 24;
	private static final int EXTRA_LARGE_SPACING = 32;

	public static String userId = "";

	// UI 组件
	private JTextField userNameInput;
	private JPasswordField passwordInput;
	private JButton loginButton;
	private JButton resetButton;
	private JLabel statusLabel;

	public static LoginPanel instance = new LoginPanel();

	public LoginPanel() {
		super();
		initializeModernUI();
	}

	private void initializeModernUI() {
		setBackground(BACKGROUND_COLOR);
		setLayout(new BorderLayout());
		
		// 创建主容器
		JPanel mainContainer = createMainContainer();
		add(mainContainer, BorderLayout.CENTER);
	}

	private JPanel createMainContainer() {
		JPanel container = new JPanel(new GridBagLayout());
		container.setBackground(BACKGROUND_COLOR);
		container.setBorder(BorderFactory.createEmptyBorder(EXTRA_LARGE_SPACING, EXTRA_LARGE_SPACING, EXTRA_LARGE_SPACING, EXTRA_LARGE_SPACING));

		// 创建登录卡片
		JPanel loginCard = createLoginCard();
		
		GridBagConstraints gbc = new GridBagConstraints();
		gbc.gridx = 0;
		gbc.gridy = 0;
		gbc.anchor = GridBagConstraints.CENTER;
		
		container.add(loginCard, gbc);
		
		return container;
	}

	private JPanel createLoginCard() {
		JPanel card = new JPanel();
		card.setLayout(new BoxLayout(card, BoxLayout.Y_AXIS));
		card.setBackground(SURFACE_COLOR);
		card.setBorder(BorderFactory.createCompoundBorder(
			BorderFactory.createLineBorder(OUTLINE_COLOR, 1),
			BorderFactory.createEmptyBorder(EXTRA_LARGE_SPACING, EXTRA_LARGE_SPACING, EXTRA_LARGE_SPACING, EXTRA_LARGE_SPACING)
		));
		card.setPreferredSize(new Dimension(320, 400));

		// 标题区域
		JPanel titlePanel = createTitlePanel();
		card.add(titlePanel);
		card.add(Box.createVerticalStrut(EXTRA_LARGE_SPACING));

		// 输入区域
		JPanel inputPanel = createInputPanel();
		card.add(inputPanel);
		card.add(Box.createVerticalStrut(LARGE_SPACING));

		// 按钮区域
		JPanel buttonPanel = createButtonPanel();
		card.add(buttonPanel);
		card.add(Box.createVerticalStrut(MEDIUM_SPACING));

		// 状态显示区域
		statusLabel = createStatusLabel();
		card.add(statusLabel);

		return card;
	}

	private JPanel createTitlePanel() {
		JPanel titlePanel = new JPanel();
		titlePanel.setLayout(new BoxLayout(titlePanel, BoxLayout.Y_AXIS));
		titlePanel.setOpaque(false);

		JLabel titleLabel = new JLabel("AI智能助手");
		titleLabel.setFont(TITLE_FONT);
		titleLabel.setForeground(ON_SURFACE_COLOR);
		titleLabel.setAlignmentX(Component.CENTER_ALIGNMENT);

		JLabel subtitleLabel = new JLabel("请登录以继续");
		subtitleLabel.setFont(BODY_FONT);
		subtitleLabel.setForeground(ON_SURFACE_VARIANT_COLOR);
		subtitleLabel.setAlignmentX(Component.CENTER_ALIGNMENT);

		titlePanel.add(titleLabel);
		titlePanel.add(Box.createVerticalStrut(SMALL_SPACING));
		titlePanel.add(subtitleLabel);

		return titlePanel;
	}

	private JPanel createInputPanel() {
		JPanel inputPanel = new JPanel();
		inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.Y_AXIS));
		inputPanel.setOpaque(false);

		// 用户名输入
		JLabel userLabel = createFieldLabel("用户名");
		userNameInput = createModernTextField("请输入用户名");
		
		// 密码输入
		JLabel passwordLabel = createFieldLabel("密码");
		passwordInput = createModernPasswordField("请输入密码");

		// 添加回车键监听
		KeyAdapter enterListener = new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_ENTER) {
					performLogin();
				}
			}
		};
		userNameInput.addKeyListener(enterListener);
		passwordInput.addKeyListener(enterListener);

		inputPanel.add(userLabel);
		inputPanel.add(Box.createVerticalStrut(SMALL_SPACING));
		inputPanel.add(userNameInput);
		inputPanel.add(Box.createVerticalStrut(LARGE_SPACING));
		inputPanel.add(passwordLabel);
		inputPanel.add(Box.createVerticalStrut(SMALL_SPACING));
		inputPanel.add(passwordInput);

		return inputPanel;
	}

	private JLabel createFieldLabel(String text) {
		JLabel label = new JLabel(text);
		label.setFont(BODY_FONT);
		label.setForeground(ON_SURFACE_COLOR);
		label.setAlignmentX(Component.LEFT_ALIGNMENT);
		return label;
	}

	private JTextField createModernTextField(String placeholder) {
		JTextField field = new JTextField();
		field.setFont(INPUT_FONT);
		field.setPreferredSize(new Dimension(250, 45));
		field.setMaximumSize(new Dimension(Integer.MAX_VALUE, 45));
		field.setBackground(SURFACE_COLOR);
		field.setForeground(ON_SURFACE_COLOR);
		field.setBorder(BorderFactory.createCompoundBorder(
			BorderFactory.createLineBorder(OUTLINE_COLOR, 1),
			BorderFactory.createEmptyBorder(MEDIUM_SPACING, MEDIUM_SPACING, MEDIUM_SPACING, MEDIUM_SPACING)
		));

		// 占位符效果
		field.setText(placeholder);
		field.setForeground(ON_SURFACE_VARIANT_COLOR);
		field.addFocusListener(new java.awt.event.FocusAdapter() {
			public void focusGained(java.awt.event.FocusEvent evt) {
				if (field.getText().equals(placeholder)) {
					field.setText("");
					field.setForeground(ON_SURFACE_COLOR);
				}
				field.setBorder(BorderFactory.createCompoundBorder(
					BorderFactory.createLineBorder(PRIMARY_COLOR, 2),
					BorderFactory.createEmptyBorder(MEDIUM_SPACING, MEDIUM_SPACING, MEDIUM_SPACING, MEDIUM_SPACING)
				));
			}
			public void focusLost(java.awt.event.FocusEvent evt) {
				if (field.getText().trim().isEmpty()) {
					field.setText(placeholder);
					field.setForeground(ON_SURFACE_VARIANT_COLOR);
				}
				field.setBorder(BorderFactory.createCompoundBorder(
					BorderFactory.createLineBorder(OUTLINE_COLOR, 1),
					BorderFactory.createEmptyBorder(MEDIUM_SPACING, MEDIUM_SPACING, MEDIUM_SPACING, MEDIUM_SPACING)
				));
			}
		});

		return field;
	}

	private JPasswordField createModernPasswordField(String placeholder) {
		JPasswordField field = new JPasswordField();
		field.setFont(INPUT_FONT);
		field.setPreferredSize(new Dimension(250, 45));
		field.setMaximumSize(new Dimension(Integer.MAX_VALUE, 45));
		field.setBackground(SURFACE_COLOR);
		field.setForeground(ON_SURFACE_COLOR);
		field.setBorder(BorderFactory.createCompoundBorder(
			BorderFactory.createLineBorder(OUTLINE_COLOR, 1),
			BorderFactory.createEmptyBorder(MEDIUM_SPACING, MEDIUM_SPACING, MEDIUM_SPACING, MEDIUM_SPACING)
		));
		field.setEchoChar((char) 0); // 暂时显示占位符文本

		// 占位符效果（密码字段的特殊处理）
		field.setText(placeholder);
		field.setForeground(ON_SURFACE_VARIANT_COLOR);
		field.addFocusListener(new java.awt.event.FocusAdapter() {
			public void focusGained(java.awt.event.FocusEvent evt) {
				if (String.valueOf(field.getPassword()).equals(placeholder)) {
					field.setText("");
					field.setEchoChar('●');
					field.setForeground(ON_SURFACE_COLOR);
				}
				field.setBorder(BorderFactory.createCompoundBorder(
					BorderFactory.createLineBorder(PRIMARY_COLOR, 2),
					BorderFactory.createEmptyBorder(MEDIUM_SPACING, MEDIUM_SPACING, MEDIUM_SPACING, MEDIUM_SPACING)
				));
			}
			public void focusLost(java.awt.event.FocusEvent evt) {
				if (String.valueOf(field.getPassword()).trim().isEmpty()) {
					field.setEchoChar((char) 0);
					field.setText(placeholder);
					field.setForeground(ON_SURFACE_VARIANT_COLOR);
				}
				field.setBorder(BorderFactory.createCompoundBorder(
					BorderFactory.createLineBorder(OUTLINE_COLOR, 1),
					BorderFactory.createEmptyBorder(MEDIUM_SPACING, MEDIUM_SPACING, MEDIUM_SPACING, MEDIUM_SPACING)
				));
			}
		});

		return field;
	}

	private JPanel createButtonPanel() {
		JPanel buttonPanel = new JPanel();
		buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
		buttonPanel.setOpaque(false);

		// 登录按钮
		loginButton = createModernButton("登录", PRIMARY_COLOR, true);
		loginButton.addActionListener(e -> performLogin());

		// 重置按钮
		resetButton = createModernButton("重置", OUTLINE_COLOR, false);
		resetButton.addActionListener(e -> resetFields());

		buttonPanel.add(loginButton);
		buttonPanel.add(Box.createVerticalStrut(MEDIUM_SPACING));
		buttonPanel.add(resetButton);

		return buttonPanel;
	}

	private JButton createModernButton(String text, Color color, boolean filled) {
		JButton button = new JButton(text);
		button.setFont(BODY_FONT);
		button.setPreferredSize(new Dimension(250, 45));
		button.setMaximumSize(new Dimension(Integer.MAX_VALUE, 45));
		button.setFocusPainted(false);
		button.setBorderPainted(true);
		button.setCursor(new Cursor(Cursor.HAND_CURSOR));
		button.setAlignmentX(Component.CENTER_ALIGNMENT);

		if (filled) {
			button.setBackground(color);
			button.setForeground(Color.WHITE);
			button.setBorder(BorderFactory.createEmptyBorder(MEDIUM_SPACING, LARGE_SPACING, MEDIUM_SPACING, LARGE_SPACING));
		} else {
			button.setBackground(SURFACE_COLOR);
			button.setForeground(color);
			button.setBorder(BorderFactory.createCompoundBorder(
				BorderFactory.createLineBorder(color, 1),
				BorderFactory.createEmptyBorder(MEDIUM_SPACING, LARGE_SPACING, MEDIUM_SPACING, LARGE_SPACING)
			));
		}

		// 悬停效果
		button.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseEntered(java.awt.event.MouseEvent evt) {
				if (filled) {
					button.setBackground(color.darker());
				} else {
					button.setBackground(new Color(color.getRed(), color.getGreen(), color.getBlue(), 20));
				}
			}
			public void mouseExited(java.awt.event.MouseEvent evt) {
				if (filled) {
					button.setBackground(color);
				} else {
					button.setBackground(SURFACE_COLOR);
				}
			}
		});

		return button;
	}

	private JLabel createStatusLabel() {
		JLabel label = new JLabel(" ");
		label.setFont(BODY_FONT);
		label.setForeground(ON_SURFACE_VARIANT_COLOR);
		label.setAlignmentX(Component.CENTER_ALIGNMENT);
		return label;
	}

	private void performLogin() {
		String username = userNameInput.getText().trim();
		String password = String.valueOf(passwordInput.getPassword()).trim();

		// 清除占位符检查
		if (username.equals("请输入用户名") || username.isEmpty()) {
			showStatus("请输入用户名", ERROR_COLOR);
			userNameInput.requestFocus();
			return;
		}

		if (password.equals("请输入密码") || password.isEmpty()) {
			showStatus("请输入密码", ERROR_COLOR);
			passwordInput.requestFocus();
			return;
		}

		// 验证登录信息
		if ((StrUtil.equals(username, "1") && StrUtil.equals(password, "1"))
				|| (StrUtil.equals(username, "2") && StrUtil.equals(password, "2"))
				|| (StrUtil.equals(username, "3") && StrUtil.equals(password, "3"))
				|| (StrUtil.equals(username, "4") && StrUtil.equals(password, "4"))
				|| (StrUtil.equals(username, "5") && StrUtil.equals(password, "5"))) {
			
			userId = username;
			showStatus("登录成功，正在跳转...", SUCCESS_COLOR);
			
			// 延迟跳转以显示成功消息
			Timer timer = new Timer(500, e -> {
				LoginFrame.instance.setVisible(false);
				new ChatInterface().setVisible(true);
			});
			timer.setRepeats(false);
			timer.start();
			
		} else {
			showStatus("用户名或密码错误！", ERROR_COLOR);
		}
	}

	private void resetFields() {
		userNameInput.setText("请输入用户名");
		userNameInput.setForeground(ON_SURFACE_VARIANT_COLOR);
		passwordInput.setEchoChar((char) 0);
		passwordInput.setText("请输入密码");
		passwordInput.setForeground(ON_SURFACE_VARIANT_COLOR);
		showStatus(" ", ON_SURFACE_VARIANT_COLOR);
		userNameInput.requestFocus();
	}

	private void showStatus(String message, Color color) {
		statusLabel.setText(message);
		statusLabel.setForeground(color);
	}
}
